package com.stu.day17;

import java.util.concurrent.Callable;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.FutureTask;

/**
 * 本来用来演示: 练习Callable
 *  计算的任务: 1+2+3+4+....100
 *  任务拆解,拆解10个子任务,分别由10个线程去执行.
 *  [1,10] - 第一个线程去完成   =>  结果1
 *  [11,20] -> 第二个线程去完成 => 结果2
 *  [91,100] -> 第三个线程去完成 => 结果3
 *  各个子任务计算的结果总和 => 最终大任务的结果.
 * @author zy
 * @date 2025/2/18 17:55
 */
public class CallableCountDemo implements Callable<Integer> {
    private int start;
    private int end;

    public CallableCountDemo(int start, int end) {
        this.start = start;
        this.end = end;
    }

    @Override
    public Integer call() throws Exception {
        int sum = 0;
        for (int i = start; i <= end; i++) {
            sum+=i;
        }
        return sum;
    }
}
class CallableCountDemoTest{
    public static void main(String[] args) {
        //创建一个10个任务的数组
        FutureTask<Integer>[] tasks = new FutureTask[10];
        //遍历这个数组
        for (int i = 1; i <=tasks.length; i++) {
            Callable<Integer> c = new CallableCountDemo((i-1)*10+1,i*10);
            tasks[i-1] = new FutureTask<>(c);
        }
        int total = 0;
        //遍历这个任务数组
        for (FutureTask<Integer> task : tasks) {
            new Thread(task).start();
            try {
                total+=task.get();
            } catch (InterruptedException e) {
                throw new RuntimeException(e);
            } catch (ExecutionException e) {
                throw new RuntimeException(e);
            }
        }
        System.out.println("10个线程计算的总和是:"+total);
    }
}